package com.hxz.graduationdesign.util;

import com.hxz.graduationdesign.pojo.entity.Video;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.StringJoiner;

public class BilibiliVideoDataFetcher {

    private static final String API_URL = "https://api.bilibili.com/x/web-interface/view?bvid=";
    private static final String HTML_URL = "https://www.bilibili.com/video/";

    public static Video getVideoData(String bvid) {
        Video video = new Video();

        try {
            // 获取视频数据
            String urlString = API_URL + bvid;
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 设置请求头
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            connection.disconnect();

            JSONObject jsonObject = new JSONObject(content.toString());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject stat = data.getJSONObject("stat");

            String title = data.getString("title");
            String description = data.getString("desc");
            String author = data.getJSONObject("owner").getString("name");
            Long uid = data.getJSONObject("owner").getLong("mid");
            int playCount = stat.optInt("view", 0);
            int danmakuCount = stat.optInt("danmaku", 0);
            int replyCount = stat.optInt("reply", 0);
            int favoriteCount = stat.optInt("favorite", 0);
            int coinCount = stat.optInt("coin", 0);
            int shareCount = stat.optInt("share", 0);
            int likeCount = stat.optInt("like", 0);

            // 获取视频时长（从API返回的数据中获取）
            int duration = data.optInt("duration", 0);
            String durationFormatted = FormattingTool.formatDuration(duration);

            // 获取视频标签
            String htmlUrlString = HTML_URL + bvid;
            Document doc = Jsoup.connect(htmlUrlString).get();
            Elements tags = doc.select(".tag-panel .tag-link");

            // 上传时间
            Element pubdateElement = doc.selectFirst(".pubdate-ip .pubdate-ip-text");
            Date pubdate = FormattingTool.parseDate(pubdateElement.text());

            video.setBv(bvid);
            video.setDuration(durationFormatted);
            video.setDescription(description);
            video.setTitle(title);
            video.setUid(String.valueOf(uid));
            video.setCoinCount(coinCount);
            video.setCommentCount(replyCount);
            video.setDamuCount(danmakuCount);
            video.setLikeCount(likeCount);
            video.setPlayCount(playCount);
            StringJoiner sj = new StringJoiner(",");
            for (Element tag : tags) {
                sj.add(tag.text());
            }
            String tagsText = sj.toString();
            video.setTags(tagsText);
            video.setFavoriteCount(favoriteCount);
            video.setUploadTime(pubdate);
            video.setUsername(author);
            video.setShareCount(shareCount);

//            System.out.println("视频标题:" + title);
//            System.out.println("作者:" + author);
//            System.out.println("作者uid:" + uid);
//            System.out.println("粉丝数:" + followCount);
//            System.out.println("视频简介:" + description);
//            System.out.println("播放量:" + playCount);
//            System.out.println("弹幕量:" + danmakuCount);
//            System.out.println("评论数:" + replyCount);
//            System.out.println("上传时间:" + pubdate);
//            System.out.println("视频时长:" + durationFormatted);
//            System.out.println("视频标签:");
//            System.out.print("| ");
//            for (Element tag : tags) {
//                System.out.print(tag.text() + " | ");
//            }
//            System.out.println();
//            System.out.println("收藏数:" + favoriteCount);
//            System.out.println("硬币数:" + coinCount);
//            System.out.println("分享数:" + shareCount);
//            System.out.println("点赞数:" + likeCount);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return video;

    }


}